/**
 * 客户详情页面JavaScript
 * 基于Apple交互设计规范的客户详情功能
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let customerId = null;
let customerData = null;

// DOM内容加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
    loadCustomerData();
    initializeEventListeners();
});

/**
 * 初始化页面
 */
function initializePage() {
    // 从URL获取客户ID
    const urlParams = new URLSearchParams(window.location.search);
    customerId = urlParams.get('id');
    
    if (!customerId) {
        showAlert('未找到客户ID，即将返回客户列表', 'error');
        setTimeout(() => {
            window.location.href = 'customer-list.html';
        }, 2000);
        return;
    }
    
    // 设置页面标题
    document.title = `客户详情 - CRM旅游管理系统`;
}

/**
 * 初始化事件监听器
 */
function initializeEventListeners() {
    // 模态框关闭
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal-overlay')) {
            closeModal(e.target.id);
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal-overlay.show');
            if (openModal) {
                closeModal(openModal.id);
            }
        }
    });
    
    // 复制功能
    document.addEventListener('click', function(e) {
        if (e.target.matches('.copy-btn, .copy-btn *')) {
            const btn = e.target.closest('.copy-btn');
            const text = btn.getAttribute('onclick').match(/'([^']+)'/)[1];
            copyToClipboard(text);
        }
    });
}

/**
 * 加载客户数据
 */
function loadCustomerData() {
    // 显示加载状态
    showLoading();
    
    // 模拟API调用（实际项目中替换为真实API）
    setTimeout(() => {
        customerData = generateMockCustomerData();
        renderCustomerData(customerData);
        hideLoading();
    }, 800);
}

/**
 * 生成模拟客户数据
 */
function generateMockCustomerData() {
    return {
        id: customerId,
        customer_number: 'CRM2025000001',
        name: '张大爷',
        gender: '男',
        birth_date: '1955-03-15',
        age: 68,
        id_card: '110101195503151234',
        work_status: '退休',
        occupation: '退休教师',
        status: '有效客户',
        
        // 联系方式
        contact: {
            primary_phone: '13800138001',
            backup_phone: '13900138888',
            wechat: 'zhangdaye1955',
            email: 'zhangdaye@example.com',
            address: '北京市朝阳区某某街道某某小区8号楼3单元502室',
            postal_code: '100020',
            preferred_contact_method: '电话'
        },
        
        // 紧急联系人
        emergency_contacts: [
            {
                name: '张小明',
                relationship: '子女',
                phone: '13900139001',
                is_primary: true
            }
        ],
        
        // 旅游偏好
        preferences: {
            budget_range: '舒适型',
            budget_description: '3000-8000元',
            payment_preference: '微信支付',
            consumption_characteristics: ['注重品质', '追求性价比'],
            domestic_preferences: ['华北', '华东'],
            international_preferences: ['东南亚', '日韩'],
            duration_preference: '中途 (4-7天)',
            transport_preferences: ['高铁', '飞机'],
            accommodation_preference: '舒适型酒店',
            season_preferences: ['春季', '秋季']
        },
        
        // 健康状况
        health: {
            health_status: '健康良好',
            mobility_level: '行动自如',
            chronic_diseases: ['高血压 (已控制)'],
            medications: '降压药 (每日一次，早晨服用)',
            dietary_restrictions: ['低盐低脂'],
            medical_insurance_type: '城镇职工医疗保险',
            travel_insurance_info: '已购买旅游意外险',
            special_needs: '患有高血压，出行时需注意用药和饮食'
        },
        
        // 家庭信息
        family: {
            marital_status: '已婚',
            decision_style: '咨询决策',
            influence_factors: ['价格因素', '安全因素', '健康因素'],
            spouse: {
                name: '李大妈',
                age: 65,
                phone: '13900138002',
                travel_together: '经常同行',
                travel_attitude: '支持'
            },
            children: [
                {
                    name: '张小明',
                    age: 42,
                    phone: '13900139001',
                    relationship_closeness: '关系密切',
                    travel_attitude: '支持'
                }
            ]
        },
        
        // 标签
        tags: ['VIP客户', '身体健康', '易沟通', '喜欢跟团', '注重品质'],
        
        // 推荐人信息
        referrer: {
            name: '王老师',
            phone: '13600137788',
            relation: '朋友推荐',
            date: '2025-01-10'
        },
        
        // 系统信息
        system_info: {
            created_at: '2025-01-15 14:30',
            created_by: '张经理',
            updated_at: '2025-01-18 09:15',
            updated_by: '李顾问',
            version: 'v1.3'
        }
    };
}

/**
 * 渲染客户数据到页面
 */
function renderCustomerData(data) {
    // 更新页面标题和面包屑
    document.title = `${data.name} - 客户详情 - CRM旅游管理系统`;
    
    // 渲染客户头部信息
    renderCustomerHeader(data);
    
    // 渲染各个信息卡片
    renderBasicInfo(data);
    renderContactInfo(data);
    renderEmergencyContacts(data);
    renderPreferences(data);
    renderHealthInfo(data);
    renderFamilyInfo(data);
    renderSidebarInfo(data);
}

/**
 * 渲染客户头部信息
 */
function renderCustomerHeader(data) {
    // 更新头像
    const avatar = document.querySelector('.customer-avatar-large');
    if (avatar) {
        avatar.textContent = data.name.charAt(0);
    }
    
    // 更新客户姓名
    const nameElement = document.querySelector('.customer-name');
    if (nameElement) {
        nameElement.textContent = data.name;
    }
    
    // 更新客户编号
    const numberElement = document.querySelector('.customer-number');
    if (numberElement) {
        numberElement.textContent = data.customer_number;
    }
    
    // 更新性别
    const genderElement = document.querySelector('.customer-gender');
    if (genderElement) {
        genderElement.textContent = data.gender;
        genderElement.className = `customer-gender ${data.gender === '男' ? 'male' : 'female'}`;
    }
    
    // 更新年龄
    const ageElement = document.querySelector('.customer-age');
    if (ageElement) {
        ageElement.textContent = `${data.age}岁`;
    }
}

/**
 * 渲染基础信息
 */
function renderBasicInfo(data) {
    const infoItems = {
        '客户姓名': data.name,
        '性别': data.gender,
        '出生日期': data.birth_date,
        '年龄': `${data.age}岁`,
        '身份证号': data.id_card,
        '工作状态': data.work_status,
        '职业信息': data.occupation || '无',
        '客户状态': data.status
    };
    
    const container = document.querySelector('.info-card .info-grid');
    if (container) {
        container.innerHTML = '';
        
        Object.entries(infoItems).forEach(([label, value]) => {
            const item = createInfoItem(label, value);
            container.appendChild(item);
        });
    }
}

/**
 * 渲染联系方式
 */
function renderContactInfo(data) {
    const contact = data.contact;
    const infoItems = {
        '主要手机': contact.primary_phone,
        '备用手机': contact.backup_phone || '无',
        '微信号': contact.wechat || '无',
        '电子邮箱': contact.email || '无',
        '通讯地址': contact.address || '无',
        '邮政编码': contact.postal_code || '无',
        '偏好联系方式': contact.preferred_contact_method
    };
    
    const container = document.querySelectorAll('.info-card .info-grid')[1];
    if (container) {
        container.innerHTML = '';
        
        Object.entries(infoItems).forEach(([label, value]) => {
            const item = createInfoItem(label, value, label === '主要手机');
            container.appendChild(item);
        });
    }
}

/**
 * 创建信息项元素
 */
function createInfoItem(label, value, includeActions = false) {
    const item = document.createElement('div');
    item.className = 'info-item';
    if (label === '通讯地址') {
        item.classList.add('full-width');
    }
    
    const labelEl = document.createElement('label');
    labelEl.className = 'info-label';
    labelEl.textContent = label;
    
    const valueEl = document.createElement('span');
    valueEl.className = 'info-value';
    
    if (includeActions && label === '主要手机') {
        valueEl.innerHTML = `
            <i class="fas fa-mobile-alt"></i>
            ${value}
            <button class="copy-btn" onclick="copyToClipboard('${value.replace(/\*/g, '')}')" title="复制">
                <i class="fas fa-copy"></i>
            </button>
        `;
    } else if (label === '客户状态') {
        valueEl.innerHTML = `<span class="status-badge ${getStatusClass(value)}">${value}</span>`;
    } else {
        valueEl.textContent = value;
    }
    
    item.appendChild(labelEl);
    item.appendChild(valueEl);
    
    return item;
}

/**
 * 获取状态样式类
 */
function getStatusClass(status) {
    const statusMap = {
        '有效客户': 'status-active',
        '潜在客户': 'status-potential',
        '已成交客户': 'status-deal',
        '无效客户': 'status-inactive',
        '黑名单': 'status-blacklist'
    };
    return statusMap[status] || 'status-default';
}

/**
 * 返回上一页
 */
function goBack() {
    // 检查是否有历史记录
    if (window.history.length > 1) {
        window.history.back();
    } else {
        // 如果没有历史记录，跳转到客户列表
        window.location.href = 'customer-list.html';
    }
}

/**
 * 编辑客户
 */
function editCustomer() {
    if (customerId) {
        window.location.href = `customer-form.html?id=${customerId}`;
    }
}

/**
 * 拨打电话
 */
function callCustomer() {
    if (customerData && customerData.contact.primary_phone) {
        // 实际项目中这里会调用电话系统API
        showAlert(`正在为您拨打 ${customerData.contact.primary_phone}...`, 'info');
    }
}

/**
 * 发送短信
 */
function sendMessage() {
    if (customerData && customerData.contact.primary_phone) {
        // 实际项目中这里会打开短信发送界面
        showAlert('正在打开短信发送界面...', 'info');
    }
}

/**
 * 显示更多操作
 */
function showMoreActions() {
    showConfirmModal('更多操作', '请选择要执行的操作：', [
        { text: '添加备注', action: addNote },
        { text: '查看历史', action: viewHistory },
        { text: '删除客户', action: deleteCustomer, destructive: true }
    ]);
}

/**
 * 编辑基础信息
 */
function editBasicInfo() {
    window.location.href = `customer-form.html?id=${customerId}#basic`;
}

/**
 * 编辑联系方式
 */
function editContactInfo() {
    window.location.href = `customer-form.html?id=${customerId}#contact`;
}

/**
 * 编辑紧急联系人
 */
function editEmergencyContacts() {
    window.location.href = `customer-form.html?id=${customerId}#emergency`;
}

/**
 * 编辑旅游偏好
 */
function editTravelPreferences() {
    window.location.href = `customer-form.html?id=${customerId}#preferences`;
}

/**
 * 编辑健康信息
 */
function editHealthInfo() {
    window.location.href = `customer-form.html?id=${customerId}#health`;
}

/**
 * 编辑家庭信息
 */
function editFamilyInfo() {
    window.location.href = `customer-form.html?id=${customerId}#family`;
}

/**
 * 编辑标签
 */
function editTags() {
    window.location.href = `customer-form.html?id=${customerId}#tags`;
}

/**
 * 拨打紧急联系人电话
 */
function callEmergencyContact(phone) {
    showAlert(`正在为您拨打紧急联系人 ${phone}...`, 'info');
}

/**
 * 发送紧急联系人短信
 */
function sendEmergencyMessage(phone) {
    showAlert(`正在为您发送短信到 ${phone}...`, 'info');
}

/**
 * 创建销售机会
 */
function createOpportunity() {
    // 实际项目中跳转到销售机会创建页面
    showAlert('正在跳转到销售机会创建页面...', 'info');
}

/**
 * 安排邀约活动
 */
function scheduleActivity() {
    // 实际项目中跳转到活动安排页面
    showAlert('正在跳转到邀约活动安排页面...', 'info');
}

/**
 * 添加跟进记录
 */
function addFollowup() {
    // 实际项目中打开跟进记录添加界面
    showAlert('正在打开跟进记录添加界面...', 'info');
}

/**
 * 查看服务历史
 */
function viewHistory() {
    // 实际项目中跳转到历史记录页面
    window.location.href = `customer-history.html?id=${customerId}`;
}

/**
 * 添加备注
 */
function addNote() {
    const note = prompt('请输入备注内容：');
    if (note && note.trim()) {
        showAlert('备注添加成功', 'success');
    }
}

/**
 * 删除客户
 */
function deleteCustomer() {
    showConfirmModal(
        '删除客户',
        '确定要删除该客户吗？此操作不可撤销。',
        [
            { text: '取消', action: () => {} },
            { text: '确定删除', action: confirmDeleteCustomer, destructive: true }
        ]
    );
}

/**
 * 确认删除客户
 */
function confirmDeleteCustomer() {
    showAlert('客户删除成功', 'success');
    setTimeout(() => {
        window.location.href = 'customer-list.html';
    }, 1500);
}

/**
 * 复制到剪贴板
 */
function copyToClipboard(text) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
            showAlert('复制成功', 'success');
        }).catch(() => {
            fallbackCopyToClipboard(text);
        });
    } else {
        fallbackCopyToClipboard(text);
    }
}

/**
 * 备用复制方法
 */
function fallbackCopyToClipboard(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        document.execCommand('copy');
        showAlert('复制成功', 'success');
    } catch (err) {
        showAlert('复制失败，请手动复制', 'error');
    }
    
    document.body.removeChild(textArea);
}

/**
 * 显示确认模态框
 */
function showConfirmModal(title, message, actions) {
    const modal = document.getElementById('action-confirm-modal');
    if (!modal) return;
    
    // 更新标题和消息
    const titleEl = modal.querySelector('.modal-title');
    const messageEl = modal.querySelector('#confirm-message');
    
    if (titleEl) titleEl.textContent = title;
    if (messageEl) messageEl.textContent = message;
    
    // 更新按钮
    const footer = modal.querySelector('.modal-footer');
    if (footer && actions.length <= 2) {
        footer.innerHTML = '';
        
        actions.forEach(action => {
            const btn = document.createElement('button');
            btn.className = action.destructive ? 'btn btn-destructive' : 'btn btn-outline';
            btn.textContent = action.text;
            btn.addEventListener('click', () => {
                action.action();
                closeModal('action-confirm-modal');
            });
            footer.appendChild(btn);
        });
    }
    
    modal.classList.add('show');
}

/**
 * 关闭模态框
 */
function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('show');
    }
}

/**
 * 显示加载状态
 */
function showLoading() {
    // 可以添加全局加载指示器
    console.log('Loading customer data...');
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    console.log('Customer data loaded');
}

/**
 * 显示提示信息
 */
function showAlert(message, type = 'info') {
    // 创建提示元素
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.style.cssText = `
        position: fixed;
        top: 80px;
        right: 20px;
        z-index: 9999;
        opacity: 0;
        transform: translateY(-20px);
        transition: all 0.3s ease;
        max-width: 300px;
        padding: 12px 16px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        display: flex;
        align-items: center;
        gap: 8px;
    `;
    
    // 根据类型设置样式
    const styles = {
        info: { bg: 'rgba(0, 122, 255, 0.1)', color: '#007AFF', icon: 'fa-info-circle' },
        success: { bg: 'rgba(52, 199, 89, 0.1)', color: '#34C759', icon: 'fa-check-circle' },
        warning: { bg: 'rgba(255, 149, 0, 0.1)', color: '#FF9500', icon: 'fa-exclamation-triangle' },
        error: { bg: 'rgba(255, 59, 48, 0.1)', color: '#FF3B30', icon: 'fa-times-circle' }
    };
    
    const style = styles[type] || styles.info;
    alert.style.backgroundColor = style.bg;
    alert.style.color = style.color;
    alert.style.border = `1px solid ${style.color}25`;
    
    alert.innerHTML = `
        <i class="fas ${style.icon}" style="flex-shrink: 0;"></i>
        <span style="font-size: 14px;">${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(alert);
    
    // 显示动画
    setTimeout(() => {
        alert.style.opacity = '1';
        alert.style.transform = 'translateY(0)';
    }, 10);
    
    // 自动移除
    setTimeout(() => {
        alert.style.opacity = '0';
        alert.style.transform = 'translateY(-20px)';
        setTimeout(() => {
            if (document.body.contains(alert)) {
                document.body.removeChild(alert);
            }
        }, 300);
    }, 3000);
}